import datetime

from rest_framework.decorators import action
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from apps.gatherings.models import Gathering
from apps.gatherings.serializers import GatheringListserializer, GatheringDetailserializer
import pytz
utc = pytz.UTC

class GatheringsViewSet(ModelViewSet):
     queryset = Gathering.objects.all()
     # serializer_class = GatheringListserializer
     def get_serializer(self, *args, **kwargs):
         if self.action == 'list':
             return GatheringListserializer(*args, **kwargs)  # 列表

         elif self.action == 'retrieve':
             return GatheringDetailserializer(*args, **kwargs) # 详情

         elif self.action == 'join':
            return GatheringDetailserializer(*args, **kwargs)


     @action(methods=['get'],detail=False)
     def list(self, request):
         gathering = Gathering.objects.all()
         serializer = self.get_serializer(gathering)

         page = self.paginate_queryset(gathering)
         if page is not None:
             serializer = self.get_serializer(page, many=True)
             return self.get_paginated_response(serializer.data)

         serializer = self.get_serializer(gathering, many=True)
         return Response(serializer.data)

     @action(methods=['get'], detail=True)
     def retrieve(self, request, pk):
         gathering = Gathering.objects.get(id=pk)
         serializer = self.get_serializer(gathering)
         return Response(serializer.data)

class GatherJoinView(APIView):

     permission_classes = [IsAuthenticated,]
     def post(self,request, pk):
        gathering = Gathering.objects.get(id=pk)
        user = request.user
        # 报名活动的所有用户
        gathering_user = gathering.users.all()
        if user not in gathering_user:
             gathering.users.add(user)

             data = {
                 'message': '报名成功',
                 'success': True
             }
             return Response(data)
        else:
            data = {
                     'message': '您已经报过了，请不要重复报名',
                     'success': False
                 }

            return Response(data)


    # def post(self, request, pk):
    #     gathering = Gathering.objects.get(id=pk)
    #     now_datetime = datetime.datetime.now()
    #     if now_datetime > gathering.endrolltime:
    #         return Response({'success': False, 'message': '报名时间已过'})
    #     user = request.user
    #     if user in gathering.users.all():
    #         gathering.users.remove(user)
    #         return Response({'success': True, 'message': '取消成功'})
    #     gathering.users.add(user)
    #     return Response({'success': True, 'message': '参加成功'})













